package cn.ecpay.unionpay.settle.notify;

import cn.ecpay.unionpay.settle.Common.DateUtil;
import cn.ecpay.unionpay.settle.Common.RespCode;
import cn.ecpay.unionpay.settle.dao.SingleFundSettlementDao;
import cn.ecpay.unionpay.settle.entity.db.TPvFundSettleSingle;
import cn.ecpay.unionpay.settle.util.CommonBase;
import cn.ecpay.unionpay.settle.util.FsasService;
import cn.ecpay.unionpay.settle.util.LogUtil;
import org.rex.db.exception.DBException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * 单笔结算异步通知
 * Created by zhaoyanzeng on 2018/11/26.
 */
@Component
public class SingleFundSettlementNotify {

    @Resource
    private SingleFundSettlementDao singleFundSettlementDao;

    public void singleFundSettlement(Map<String,String> reqParam)
            throws ServletException, IOException {
        LogUtil.writeLog("单笔结算异步通知开始");
        LogUtil.printRequestLog(reqParam);
        TPvFundSettleSingle fundSettleSingle = convert(reqParam);
        if (!FsasService.validate(reqParam, CommonBase.encoding)) {
            LogUtil.writeLog("验证签名结果[失败].");
            fundSettleSingle.setNotifyValidate("0");
        } else {
            LogUtil.writeLog("验证签名结果[成功].");
            fundSettleSingle.setNotifyValidate("1");
            String respCode = reqParam.get("respCode");
            if (RespCode.RESP_SUCCESS.equals(respCode)) {
                //TODO 成功
            } else {
                //TODO 失败
            }
            LogUtil.writeLog("respCode=" + respCode);
        }
        try {
            singleFundSettlementDao.updateNotify(fundSettleSingle);
        } catch (DBException e) {
            LogUtil.writeLog("单笔结算异步通知保存失败");
            e.printStackTrace();
        }
        LogUtil.writeLog("单笔结算异步通知结束");
    }

    private TPvFundSettleSingle convert(Map<String, String> reqParam) {
        TPvFundSettleSingle fundSettleSingle = new TPvFundSettleSingle();
        fundSettleSingle.setTxnNo(reqParam.get("txnNo"));
        fundSettleSingle.setNotifyRespCode(reqParam.get("respCode"));
        fundSettleSingle.setNotifyRespMsg(reqParam.get("respMsg"));
        fundSettleSingle.setNotifyTime(DateUtil.getDateTo19(new Date()));
        fundSettleSingle.setIsNotify("1");
        return fundSettleSingle;
    }
}
